//
//  LTImagePreviewViewController.m
//  LocalTravel
//
//  Created by zheng ji on 14-3-17.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTImagePreviewViewController.h"

@interface LTImagePreviewViewController ()
{
    NSArray* _arrayImageList;
    NSString* _imageBaseUrl;
    NSString* _sizeCode;
    NSInteger _imageWith;
    NSInteger _imageHeight;
    UIScrollView* _scrollView;
    NSString* _sceneryId;
    int _imageBaseTag;
    UIActivityIndicatorView *_activityView;
    UILabel* _loadMoreTip;
}
@end

@implementation LTImagePreviewViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _imageBaseTag=100;
    
    _imageWith=740;
    _imageHeight=350;
    
    
        //_activityIndicator.hidden=YES;
    [self initUI];
    
    
	// Do any additional setup after loading the view.
}
-(void)viewDidAppear:(BOOL)animated{
    [self createActivityIndicatorView:_scrollView];
   
   // [NSThread detachNewThreadSelector:@selector(loadImageList:) toTarget:self withObject:nil];
    [self loadImageList];
    
    [self removeActivityIndicatorView];
   
    
    
}
-(void)closeButtonClick:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)pageControlChange:(UIPageControl*) pageControl{
    
       NSInteger page = pageControl.currentPage;
    

      [self showImageInScrollView:page -1 +_imageBaseTag];
      [self showImageInScrollView:page   +_imageBaseTag];
      [self showImageInScrollView:page +1  +_imageBaseTag];
    
         CGRect bounds = _scrollView.bounds;
         bounds.origin.x = CGRectGetWidth(bounds) * page;
         bounds.origin.y = 0;
         [_scrollView scrollRectToVisible:bounds animated:YES];
}
 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
 {
        CGFloat pageWidth = CGRectGetWidth(_scrollView.frame);
         NSInteger page = floor((_scrollView.contentOffset.x -pageWidth/2)/pageWidth) +1;
        // _pageControl.currentPage = page;
    
    [self showImageInScrollView:page -1 +_imageBaseTag];
     [self showImageInScrollView:page   +_imageBaseTag];
     [self showImageInScrollView:page +1  +_imageBaseTag];
     //if(page >0 || page<=_arrayImageList.count){
       self.navigationItem.title=[NSString stringWithFormat:@"%d/%d",page+1,_arrayImageList.count];
     //}

     
   }
-(void) initUI{
    CGRect frame=CGRectMake(0, 0, _imageWith, _imageHeight+35);
    
      self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStyleBordered target:self action:@selector(closeButtonClick:)];
    //self.navigationItem.rightBarButtonItems=[NSArray arrayWithObject:closeButton];
    
    UINavigationController* navi= self.navigationController;
    
    navi.view.superview.frame =frame;
    navi.view.superview.center =  CGPointMake(land_full_width/2, land_full_height/2);
    
       self.navigationItem.title=[NSString stringWithFormat:@"%@[图片加载中...]",[self.dictScenery objectForKey:@"sceneryName"]];
       // self.navigationItem.title=[NSString stringWithFormat:@"1/%d",_arrayImageList.count];
     _scrollView=[[UIScrollView alloc ]initWithFrame:frame];
    _scrollView.pagingEnabled=YES;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.showsVerticalScrollIndicator=NO;
    _scrollView.contentSize=CGSizeMake(_imageWith*_arrayImageList.count, _imageHeight);
        _scrollView.delegate=self;
      [self.view addSubview:_scrollView];
/*
    int startX=0;
    for(int i=0;i<_arrayImageList.count;i++){
        
       UIImageView* imageView=[[UIImageView alloc]initWithFrame:CGRectMake(startX, 0, _imageWith, _imageHeight)];
        imageView.tag=_imageBaseTag + i;
        [_scrollView addSubview:imageView];

        startX=startX + _imageWith;
    }
       
 
        
     if(_arrayImageList.count>0){
         [self showImageInScrollView:_imageBaseTag ];
     }
     if(_arrayImageList.count>1){
         [self showImageInScrollView:_imageBaseTag +1];
     }
     
 */
    
    //[self showImageInScrollView:_imageBaseTag];
    
    
}
-(void)removeActivityIndicatorView{
    [_activityView removeFromSuperview];
    [_loadMoreTip removeFromSuperview];
}
-(void)createActivityIndicatorView:(UIView*) imageView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=imageView.frame.size.width/2-50;
    activityFrame.origin.y=imageView.frame.size.height/2;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [imageView addSubview:_activityView];
    [imageView addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}

-(void)showImageInScrollView:(int)index{
    if(index <_imageBaseTag || index>=(_imageBaseTag + _arrayImageList.count))return ;
    NSString* imageName=[_arrayImageList objectAtIndex:index-_imageBaseTag];
    
    NSString* localImagePath=[NSString stringWithFormat:@"%@/%@_%@",[CommonConfigUtil getImageLocalPath],_sizeCode,[imageName stringByReplacingOccurrencesOfString:@"/" withString:@"_"]];
    
    NSString* netImagePath=[NSString stringWithFormat:@"%@%@/%@",_imageBaseUrl,_sizeCode,imageName];
    UIImageView *imageView=(UIImageView*)[_scrollView viewWithTag:index];
  
    if(imageView ==nil){
          imageView=[[UIImageView alloc]initWithFrame:CGRectMake((index-_imageBaseTag) *_imageWith , 0, _imageWith, _imageHeight)];
        imageView.tag=  index;
        [_scrollView addSubview:imageView];
    }
 
    
    if(imageView.image !=nil)return ;
    
    [self createActivityIndicatorView:imageView];
    
    if([CommonConfigUtil existImageWithLocalPath:localImagePath]){
        //从本地读取图片
        imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
        
    }else if([CommonConfigUtil writeImage:netImagePath toImagePath:localImagePath]){
        //从网络读取图片
        //imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:netImagePath]]];
        imageView.image=[[UIImage alloc] initWithContentsOfFile:localImagePath];
        
        
    }else{
        //从网络读取图片
        imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:netImagePath]]];
    }
    [self removeActivityIndicatorView];
    //[self stopActivityView:imageView];
    imageName=nil;
    localImagePath=nil;
    netImagePath=nil;
    imageView=nil;
}
-(void)readSceneryImageJsonFromNet{
    NSString* xmlData=  [LocalTravelRequest getSceneryImageList:_sceneryId page:1 pageSize:100];
    
    ImageListParse* parse=[[ImageListParse alloc]initWithXmlData:xmlData];
    NSDictionary* dictImage=[parse getScenaryImage];
    [self parseDictImage:dictImage];
    
    
    //[self writeSceneryImageJsonToLocal:dictImage];
    [NSThread detachNewThreadSelector:@selector(writeSceneryImageJsonToLocal:) toTarget:self withObject:dictImage];
    
    
}
-(void)readSceneryImageJsonFromLocal {
    NSError* error=nil;
    NSString* localImageJson=[NSString stringWithFormat:@"%@/%@_images.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localImageJson];
    if(jsonData !=nil){
        NSDictionary* dictImage=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || dictImage==nil ) {
            [self readSceneryImageJsonFromNet];//从网络获取
        }else{
            [self parseDictImage:dictImage];

        }
    }

}
//将景点图片json保存到本地
-(void) writeSceneryImageJsonToLocal:(NSDictionary*)dictImage{
    if(dictImage ==nil || dictImage.count==0) return;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_images.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSError* error=nil;
    NSData* jsonData= [NSJSONSerialization dataWithJSONObject:dictImage options:NSJSONWritingPrettyPrinted error:nil];
    if(!error && jsonData !=nil){
        @try{
            [jsonData writeToFile:localCityJson atomically:YES];
            jsonData=nil;
        }@catch(NSException* ex) {
            
        }
    }
    
    
}
-(void)parseDictImage:(NSDictionary*)dictImage{
    
    
    if(dictImage!=nil){
        _arrayImageList=[dictImage objectForKey:@"imageList"];
        _imageBaseUrl=[dictImage objectForKey:@"imageBaseUrl"];
        _sizeCode=[dictImage objectForKey:@"sizeCode"];
        NSRange range= [_sizeCode rangeOfString:@"_"];
        if(range.length>0){
            
            _imageWith=[[_sizeCode substringToIndex:range.location  ] intValue];
            _imageHeight =[[_sizeCode substringFromIndex:range.location +1] intValue];
        }
    }

}
-(void)loadImageList{
    if(self.dictScenery==nil) return ;
    
    _sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
 
    
    
    NSString* localImageJson=[NSString stringWithFormat:@"%@/%@_images.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    if([CommonConfigUtil existFileWithLocalPath:localImageJson]){
        
        
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localImageJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readSceneryImageJsonFromNet];
                
            }else{
                //从本地获取
                [self readSceneryImageJsonFromLocal];
            }
        }else{
            //从网络获取
            [self readSceneryImageJsonFromNet];
        }
        
        
        
    }else{
        //从网络获取
        [self readSceneryImageJsonFromNet];
        
    }

    //更加实际图片数据重置scroll frame
    _scrollView.contentSize=CGSizeMake(_imageWith*_arrayImageList.count, _imageHeight);
    
    [_scrollView setFrame:CGRectMake(0, 0, _imageWith, _imageHeight)];
    
    if(_arrayImageList.count>0){
        self.navigationItem.title=[NSString stringWithFormat:@"1/%d",_arrayImageList.count];
        [self showImageInScrollView:_imageBaseTag ];
    }
    if(_arrayImageList.count>1){
        [self showImageInScrollView:_imageBaseTag +1];
    }

    
    
}




-(void)dealloc{
    _scrollView=nil;
   // _pageControl=nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
